import { Request } from 'express'
import { OutgoingHttpHeaders } from 'http'
import { Entity, ObjectId, ObjectIdColumn, Column, Index, BaseEntity, BeforeInsert } from 'typeorm'
import dayjs from 'dayjs'
import RequestErrorInfo from './RequestErrorInfo'

@Entity('request_logs')
export default class RequestLog extends BaseEntity {
  @ObjectIdColumn({ comment: 'ID' })
  _id: ObjectId

  @Column('number', { nullable: true, default: null, comment: '用户ID' })
  @Index('user_id_index', { sparse: true })
  user_id: number | null

  @Column('string', { comment: '请求时间' })
  @Index('request_at_index')
  request_at: string

  @Column('string', { comment: '请求方式' })
  method: string

  @Column('string', { comment: '请求来源' })
  origin?: string

  @Column('string', { comment: '路由路径', nullable: true })
  route: string

  @Column('string', { comment: '客户端IP', nullable: true })
  client_ip?: string

  @Column('number', { comment: '请求耗时' })
  duration: number

  @Column('json', { comment: '请求头' })
  req_headers: Request['headers']

  @Column('json', { comment: '请求参数', nullable: true })
  req_params: Record<string, any>

  @Column('number', { comment: '响应状态' })
  @Index('res_status_index')
  res_status: number

  @Column('json', { comment: '响应头' })
  res_headers: OutgoingHttpHeaders

  @Column('json', { comment: '响应数据', nullable: true })
  res_body: any

  @Column('json', { comment: '响应Cookies', nullable: true })
  res_cookies?: string

  @Column('boolean', { comment: '是否有错误', default: false })
  @Index('has_error_index')
  has_error: boolean

  @Column(_type => RequestErrorInfo)
  error_info?: RequestErrorInfo

  @Column('string', { comment: '创建时间' })
  @Index('created_at_index')
  created_at: string

  // 新增前添加创建时间字段
  @BeforeInsert()
  updateCreatedAt() {
    this.created_at = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
}
